package com.lyy.cloud.server.config;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyy.cloud.utils.enumeration.ResultCode;
import com.lyy.cloud.utils.result.Result;
import com.lyy.cloud.utils.result.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义熔断异常类
 * @author liushiwei
 */
@Slf4j
@Component
public class ServerSentinelBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        // 自定义封装的类，可以定义
        Result restObject = null;

        if (e instanceof FlowException) {
            log.info("................sentinel 限流.....................");
            // 限流
            restObject = ResultUtils.wrapFailEnum(ResultCode.SENTINEL_FLOW);
        } else if (e instanceof DegradeException) {
            log.info("................sentinel 降级.....................");
            // 降级
            restObject = ResultUtils.wrapFailEnum(ResultCode.SENTINEL_DEGRADE);
        } else if (e instanceof ParamFlowException) {
            log.info("................sentinel 热点参数.....................");
            // 热点参数
            restObject = ResultUtils.wrapFailEnum(ResultCode.SENTINEL_PARAM_FLOW);
        } else if (e instanceof SystemBlockException) {
            log.info("................sentinel 系统保护.....................");
            // 系统保护
            restObject = ResultUtils.wrapFailEnum(ResultCode.SENTINEL_SYSTEM_BLOCK);
        } else if (e instanceof AuthorityException) {
            log.info("................sentinel 授权规则.....................");
            // 授权规则
            restObject = ResultUtils.wrapFailEnum(ResultCode.SENTINEL_AUTHORITY);
        }
        //返回json数据
        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), restObject);
    }
}
